package com.atguigu.tingshu.search.config;

import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * Description:
 *
 * @author Yanxinhao on 2025/2/7
 */
@Configuration
public class RedissonAutoConfiguration {

    @Autowired
    private StringRedisTemplate redisTemplate;


    //自定义一个Redisson客户端Bean对象
    @Bean
    public RedissonClient redissonClient(){
        //创建redisson的配置对象
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.146.100:6379");
        return Redisson.create(config);
    }

    //自定义一个布隆过滤器Bean对象
    @Bean
    public RBloomFilter bloomFilter(RedissonClient client){

        //因为每次我们重启服务都会调用这个布隆过滤器的初始化逻辑
        //其实我们只要初始化一次就够了，不需要每次都初始化，因为这里我们引入分布式锁，来进行幂等性保障
        //即初始化布隆过滤器的业务只会执行一次
        String bloomFilterLockName = "albumIdBloomFilter:lock";
        Boolean isFirstTimeToInit = redisTemplate.opsForValue().setIfAbsent(bloomFilterLockName, "1");

        RBloomFilter<Object> albumIdBloomFilter = client.getBloomFilter("albumIdBloomFilter");

        if (isFirstTimeToInit){
            //初始化布隆过滤器
            albumIdBloomFilter.tryInit(1000000L,0.03);
            return albumIdBloomFilter;
        } else {
            return albumIdBloomFilter;
        }


    }
}